package com.lib.common.view;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RadialGradient;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.animation.AccelerateInterpolator;
import android.widget.Button;

public class RippleView extends Button {

	private static final int DEFAULT_RADIUS = 20;

	private int mX;

	private int mY;

	private Paint mPaint;

	private float mRadius;

	private ObjectAnimator mAnimator;

	public RippleView(Context context) {

		this(context, null);
	}

	public RippleView(Context context, AttributeSet attrs) {

		this(context, attrs, 0);
	}

	public RippleView(Context context, AttributeSet attrs, int defStyle) {

		super(context, attrs, defStyle);

		mPaint = new Paint();
		setLayerType(LAYER_TYPE_SOFTWARE, mPaint);
	}

	public void setRadius(int radius) {

		mRadius = radius;
		if (mRadius > 0) {
			RadialGradient radialGradient = new RadialGradient(mX, mY, mRadius, 0xFFFFFFFF, 0x8812A0FF,
				Shader.TileMode.CLAMP);
			mPaint.setShader(radialGradient);
		}
		invalidate();
	}

	@Override
	protected void onDraw(Canvas canvas) {

		super.onDraw(canvas);
		canvas.drawCircle(mX, mY, mRadius, mPaint);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {

		int action = event.getAction();
		switch (action) {
		case MotionEvent.ACTION_MOVE:
		case MotionEvent.ACTION_DOWN:

			mX = (int) event.getX();
			mY = (int) event.getY();
			setRadius(DEFAULT_RADIUS);

			break;
		case MotionEvent.ACTION_UP:

			showAnim();
			break;
		}
		super.onTouchEvent(event);
		return true;
	}

	private void showAnim() {

		if (mAnimator != null && mAnimator.isRunning()) {
			mAnimator.cancel();
		}

		if (mAnimator == null) {
			mAnimator = ObjectAnimator.ofInt(this, "radius", DEFAULT_RADIUS, (int) (Math.sqrt(
				(getWidth() * getWidth()) + (getHeight() * getHeight()))));
		}
		mAnimator.setInterpolator(new AccelerateInterpolator());
		mAnimator.start();
		mAnimator.addListener(new Animator.AnimatorListener() {

			@Override
			public void onAnimationStart(Animator animation) {

			}

			@Override
			public void onAnimationEnd(Animator animation) {

				setRadius(0);
			}

			@Override
			public void onAnimationCancel(Animator animation) {

			}

			@Override
			public void onAnimationRepeat(Animator animation) {

			}
		});
	}
}